
package com.kamikaze.lamg;

import com.waps.AppConnect;
import com.waps.UpdatePointsNotifier;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.HashMap;

public class MovieHomeActivity extends Activity {

    private MovieDBHelper dbHelper;

    private Page page;

    private LinearLayout progressBar;

    private ViewPager mPager;

    private Button btnPrev;

    private Button btnNext;

    private GridViewAdapter adapter;

    private MoviePagerAdapter moviePagerAdapter;

    private AppConnect appConnect;

    private ArrayList<GridViewAdapter> adapters;

    private HashMap<Integer, ImageView> purchasedInvisableViews;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_main);
        progressBar = (LinearLayout) findViewById(R.id.progressBar);
        btnPrev = (Button) findViewById(R.id.btnPrev);
        btnNext = (Button) findViewById(R.id.btnNext);
        dbHelper = new MovieDBHelper(this);
        page = new Page(dbHelper);
        page.setCurrentPage(1);
        setNextPrevVisibility(0);
        mPager = (ViewPager) findViewById(R.id.pager);
        moviePagerAdapter = new MoviePagerAdapter(this);
        mPager.setAdapter(moviePagerAdapter);
        mPager.setOnPageChangeListener(changeListener);
        setProgressBar(page.getTotalPage(), 1);
        appConnect = AppConnect.getInstance(this);
        adapters = new ArrayList<GridViewAdapter>();
        purchasedInvisableViews = new HashMap<Integer, ImageView>();

    }

    @Override
    protected void onDestroy() {
        dbHelper.closeDatabase();
        appConnect.finalize();
        for (GridViewAdapter adapter : adapters) {
            adapter.getCursor().close();

        }
        adapters.clear();
        adapters = null;
        purchasedInvisableViews.clear();
        purchasedInvisableViews = null;
        super.onDestroy();
    }

    private void setNextPrevVisibility(int position) {
        if (position <= 0) {
            btnPrev.setVisibility(View.INVISIBLE);
        } else {
            btnPrev.setVisibility(View.VISIBLE);
        }
        if (position >= page.getTotalPage() - 1) {
            btnNext.setVisibility(View.INVISIBLE);
        } else {
            btnNext.setVisibility(View.VISIBLE);
        }

    }

    OnPageChangeListener changeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            setProgressBar(page.getTotalPage(), position + 1);
            setNextPrevVisibility(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, 1, R.string.help);
        menu.add(0, 2, 2, R.string.feedback);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case 1:
                intent = new Intent(this, HelpActivity.class);
                startActivity(intent);
                return true;
            case 2:
                appConnect.showFeedback();
                return true;
        }
        return false;

    }

    /**
     * 设置顶部进度条
     * 
     * @param total
     * @param current
     */
    private void setProgressBar(int total, int current) {
        progressBar.removeAllViews();
        // ImageView iv;
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        LinearLayout l;

        int totalWidth = displayMetrics.widthPixels;
        int imageWidth = (int) (totalWidth * 4 / 5 / total);

        for (int i = 1; i <= total; i++) {
            l = new LinearLayout(this);
            l.setLayoutParams(new LayoutParams(imageWidth, LayoutParams.FILL_PARENT));
            // l.setWeightSum(1.0f);

            l.setPadding(1, 1, 1, 1);
            LinearLayout l2 = new LinearLayout(this);
            l2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            // l.setWeightSum(1.0f);
            // iv = new ImageView(this);
            if (i == current) {
                l2.setBackgroundColor(Color.parseColor("#99004C"));
            } else {
                l2.setBackgroundColor(Color.rgb(255, 255, 255));
            }
            l.addView(l2);

            progressBar.addView(l);
            // if (i != total) {
            // progressBar.addView(l);
            // }
        }
    }

    class Page {

        int totalPage;

        int currentPage;

        Page(MovieDBHelper dbHelper) {
            helper = dbHelper;
            totalPage = getTotalPage();
        }

        public void setCurrentPage(int page) {
            currentPage = page;
        }

        private MovieDBHelper helper;

        int getPrevPage(int currentPageIndex) {
            if (currentPageIndex <= 1) {
                return 1;
            } else {
                return currentPageIndex - 1;
            }
        }

        int getNextPage(int currentPageIndex) {
            if (currentPageIndex >= totalPage) {
                return totalPage;
            } else {
                return currentPageIndex + 1;
            }
        }

        int getTotalPage() {
            return (int) Math.ceil(helper.getMovieCount() / 6f);
        }

        ArrayList<MovieInfo> getMoviesInPage(int pageIndex) {
            int limit = 6;
            int offset = (pageIndex - 1) * 6;
            return dbHelper.getMovieInfos(limit, offset);
        }

        Cursor getMoviesCursorInPage(int pageIndex) {
            int limit = 6;
            int offset = (pageIndex - 1) * 6;
            return dbHelper.getMovieCursor(limit, offset);
        }

    }

    private class MoviePagerAdapter extends PagerAdapter {

        private LayoutInflater layoutInflater;

        private Context mContext;

        private GridView gvMovies;

        MoviePagerAdapter(Context context) {
            mContext = context;
        }

        @Override
        public void destroyItem(View collection, int position, Object view) {
            ((ViewPager) collection).removeView((View) view);
        }

        @Override
        public int getCount() {
            return page.totalPage;
        }

        @Override
        public Object instantiateItem(View collection, int position) {
            layoutInflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = layoutInflater.inflate(R.layout.home_item, null);
            gvMovies = (GridView) view.findViewById(R.id.gvMovies);
            page.setCurrentPage(position + 1);
            if (gvMovies.getAdapter() == null) {
                adapter = new GridViewAdapter(mContext,
                        page.getMoviesCursorInPage(page.currentPage));
                gvMovies.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                adapters.add(adapter);
            } else {
                ((CursorAdapter) gvMovies.getAdapter()).changeCursor(page
                        .getMoviesCursorInPage(page.currentPage));
            }
            gvMovies.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parentView, View view, int id, long position) {
                    Intent intent = new Intent(MovieHomeActivity.this, MovieDetailActivity.class);
                    intent.putExtra("movieId", (Integer) view.getTag());
                    startActivityForResult(intent, 1);
                }
            });
            ((ViewPager) collection).addView(view);
            return view;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (arg1);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                int id = data.getIntExtra("id", -1);
                purchasedInvisableViews.get(id).setVisibility(View.VISIBLE);
                purchasedInvisableViews.remove(id);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    class GridViewAdapter extends CursorAdapter {
        private LayoutInflater inflater;

        byte[] buff;

        ImageView ivMovieCover;

        ImageView purchasedView;

        BitmapFactory.Options opts;

        public GridViewAdapter(Context context, Cursor c) {
            super(context, c);
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            opts = new BitmapFactory.Options();
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // ivMovieCover = (ImageView) view.findViewById(R.id.movieCover);
            // buff = cursor.getBlob(cursor.getColumnIndex("frontcover"));
            // boolean purchased =
            // cursor.getInt(cursor.getColumnIndex("purchased")) == 0 ? false
            // : true;
            // if (purchased) {
            // ((ImageView)
            // view.findViewById(R.id.purchased)).setVisibility(View.VISIBLE);
            // }
            // ivMovieCover.setImageBitmap(BitmapFactory.decodeByteArray(buff,
            // 0, buff.length));
            // view.setTag(cursor.getInt(cursor.getColumnIndex("_id")));
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = inflater.inflate(R.layout.frontcover_item, null);
            ivMovieCover = (ImageView) view.findViewById(R.id.movieCover);
            buff = cursor.getBlob(cursor.getColumnIndex("frontcover"));
            int id = cursor.getInt(cursor.getColumnIndex("_id"));
            boolean purchased = cursor.getInt(cursor.getColumnIndex("purchased")) == 0 ? false
                    : true;
            purchasedView = ((ImageView) view.findViewById(R.id.purchased));
            if (purchased) {
                purchasedView.setVisibility(View.VISIBLE);
            } else {
                purchasedInvisableViews.put(id, purchasedView);
            }
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(buff, 0, buff.length, opts);
            int px = Utils.dip2px(MovieHomeActivity.this, 132f);
            opts.inSampleSize = Utils.computeSampleSize(opts, -1, px * px);
            opts.inJustDecodeBounds = false;
            ivMovieCover.setImageBitmap(BitmapFactory.decodeByteArray(buff, 0, buff.length, opts));
            view.setTag(id);
            return view;
        }

    }
}
